<template>
  <div class="backtest-result-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>回测结果详情</span>
          <el-button type="primary" size="small" @click="exportReport">导出报告</el-button>
        </div>
      </template>
      <div class="result-header">
        <div class="result-info-item">
          <div class="info-label">策略名称</div>
          <div class="info-value">{{ backtestResult?.strategyName || 'N/A' }}</div>
        </div>
        <div class="result-info-item">
          <div class="info-label">回测周期</div>
          <div class="info-value">{{ backtestResult?.startDate || 'N/A' }} 至 {{ backtestResult?.endDate || 'N/A' }}</div>
        </div>
        <div class="result-info-item">
          <div class="info-label">初始资金</div>
          <div class="info-value">{{ backtestResult?.initialCapital || 'N/A' }}</div>
        </div>
      </div>

      <div class="result-stats">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-label">总收益</div>
            <div class="stat-value">{{ backtestResult?.profit || 'N/A' }}</div>
          </div>
        </el-card>
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-label">收益率</div>
            <div class="stat-value">{{ backtestResult?.profitRate || 'N/A' }}%</div>
          </div>
        </el-card>
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-label">最大回撤</div>
            <div class="stat-value">{{ backtestResult?.maxDrawdown || 'N/A' }}%</div>
          </div>
        </el-card>
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-label">胜率</div>
            <div class="stat-value">{{ backtestResult?.winRate || 'N/A' }}%</div>
          </div>
        </el-card>
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-label">年化收益率</div>
            <div class="stat-value">{{ backtestResult?.annualReturn || 'N/A' }}%</div>
          </div>
        </el-card>
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-label">交易次数</div>
            <div class="stat-value">{{ backtestResult?.trades || 'N/A' }}</div>
          </div>
        </el-card>
      </div>

      <div class="result-charts">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>净值曲线</span>
            </div>
          </template>
          <div ref="equityChart" class="chart-container"></div>
        </el-card>
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>每日收益</span>
            </div>
          </template>
          <div ref="dailyProfitChart" class="chart-container"></div>
        </el-card>
      </div>

      <div class="result-trades">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>交易记录</span>
            </div>
          </template>
          <el-table :data="backtestResult?.tradesList || []" style="width: 100%">
            <el-table-column prop="time" label="时间" width="180" />
            <el-table-column prop="side" label="方向" width="80">
              <template #default="{ row }">
                <span :class="{ 'buy-tag': row.side === 'BUY', 'sell-tag': row.side === 'SELL' }">{{ row.side }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="价格" width="100" />
            <el-table-column prop="qty" label="数量" width="100" />
            <el-table-column prop="amount" label="金额" width="120" />
            <el-table-column prop="profit" label="收益" width="120" />
          </el-table>
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="backtestResult?.trades || 0"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts';

const route = useRoute();
const backtestResult = ref(null);
const equityChart = ref(null);
const dailyProfitChart = ref(null);
const currentPage = ref(1);
const pageSize = ref(10);

onMounted(() => {
  // 模拟获取回测结果
  fetchBacktestResult();
});

function fetchBacktestResult() {
  // 模拟API请求
  setTimeout(() => {
    // 模拟回测结果数据
    backtestResult.value = {
      id: 1,
      strategyId: 1,
      strategyName: 'MACD交叉策略',
      startDate: '2023-07-01',
      endDate: '2023-07-31',
      initialCapital: '¥10,000.00',
      profit: '¥2,345.67',
      profitRate: 23.46,
      maxDrawdown: 8.2,
      winRate: 58.3,
      annualReturn: 35.7,
      trades: 24,
      tradesList: generateMockTrades()
    };
    // 初始化图表
    initEquityChart();
    initDailyProfitChart();
  }, 500);
}

function generateMockTrades() {
  const trades = [];
  const startDate = new Date('2023-07-01');
  let price = 40000;
  let qty = 0.1;
  let isBuy = true;
  let balance = 10000;
  let position = 0;
  let totalProfit = 0;

  for (let i = 0; i < 24; i++) {
    const date = new Date(startDate);
    date.setDate(startDate.getDate() + Math.floor(i * 31 / 24));
    const time = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${Math.floor(Math.random() * 24).toString().padStart(2, '0')}:${Math.floor(Math.random() * 60).toString().padStart(2, '0')}:${Math.floor(Math.random() * 60).toString().padStart(2, '0')}`;

    // 随机波动价格
    price += price * (Math.random() - 0.48) * 0.02;
    price = parseFloat(price.toFixed(2));

    // 调整数量
    qty = parseFloat((balance * 0.2 / price).toFixed(4));

    if (isBuy) {
      // 买入
      position += qty;
      balance -= qty * price;
      trades.push({
        time,
        side: 'BUY',
        price: `¥${price}`,
        qty: qty,
        amount: `¥${(qty * price).toFixed(2)}`,
        profit: '0'
      });
    } else {
      // 卖出
      const profit = (qty * price) - (qty * (40000 + (i % 5) * 1000));
      totalProfit += profit;
      balance += qty * price;
      position -= qty;
      trades.push({
        time,
        side: 'SELL',
        price: `¥${price}`,
        qty: qty,
        amount: `¥${(qty * price).toFixed(2)}`,
        profit: `¥${profit.toFixed(2)}`
      });
    }

    isBuy = !isBuy;
  }

  return trades;
}

function initEquityChart() {
  // 模拟净值数据
  const dates = [];
  const equity = [];
  const startDate = new Date('2023-07-01');
  const endDate = new Date('2023-07-31');
  let currentDate = new Date(startDate);
  let currentEquity = 10000;
  equity.push(currentEquity);
  dates.push(formatDate(currentDate));

  while (currentDate < endDate) {
    currentDate.setDate(currentDate.getDate() + 1);
    // 模拟净值波动
    const change = currentEquity * (Math.random() - 0.48) * 0.02;
    currentEquity += change;
    equity.push(currentEquity);
    dates.push(formatDate(currentDate));
  }

  const chart = echarts.init(equityChart.value);
  const option = {
    title: {
      text: '净值曲线',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        interval: Math.floor(dates.length / 10) // 只显示10个标签
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: equity,
      type: 'line',
      smooth: true
    }]
  };
  chart.setOption(option);
  window.addEventListener('resize', () => chart.resize());
}

function initDailyProfitChart() {
  // 模拟每日收益数据
  const dates = [];
  const profits = [];
  const startDate = new Date('2023-07-01');
  const endDate = new Date('2023-07-31');
  let currentDate = new Date(startDate);

  while (currentDate < endDate) {
    dates.push(formatDate(currentDate));
    // 模拟每日收益
    const profit = (Math.random() - 0.45) * 200;
    profits.push(parseFloat(profit.toFixed(2)));
    currentDate.setDate(currentDate.getDate() + 1);
  }

  const chart = echarts.init(dailyProfitChart.value);
  const option = {
    title: {
      text: '每日收益',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        interval: Math.floor(dates.length / 10) // 只显示10个标签
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: profits,
      type: 'bar',
      itemStyle: {
        color: function(params) {
          return params.value >= 0 ? '#27AE60' : '#E74C3C';
        }
      }
    }]
  };
  chart.setOption(option);
  window.addEventListener('resize', () => chart.resize());
}

function formatDate(date) {
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
}

function exportReport() {
  // 模拟导出报告
  ElMessage({
    type: 'success',
    message: '报告导出成功'
  });
}

function handleSizeChange(val) {
  pageSize.value = val;
  // 这里可以添加分页逻辑
}

function handleCurrentChange(val) {
  currentPage.value = val;
  // 这里可以添加分页逻辑
}
</script>

<style scoped>
.backtest-result-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.result-header {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.result-info-item {
  flex: 1 1 200px;
}

.info-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.info-value {
  font-size: 16px;
  font-weight: bold;
  color: #1f2329;
}

.result-stats {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.stat-card {
  flex: 1 1 150px;
  min-width: 150px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px 0;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #1f2329;
}

.result-charts {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.chart-card {
  flex: 1;
}

.chart-container {
  width: 100%;
  height: 300px;
}

.result-trades {
  margin-top: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.buy-tag {
  color: #27AE60;
  font-weight: bold;
}

.sell-tag {
  color: #E74C3C;
  font-weight: bold;
}
</style>